import { createRouter, createWebHashHistory } from 'vue-router'
import Layout from '@/views/Layout/index.vue'
import store from '@/store'

const routes = [
  { path: '/test', component: () => import('@/views/Test') },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/', component: () => import('@/views/Home/index.vue') },
      { path: '/category/:id', component: () => import('@/views/Category/index.vue') },
      { path: '/product/:id', component: () => import('@/views/Goods/index.vue') },
      { path: '/cart', component: () => import('@/views/Cart/index.vue') },
      { path: '/settlement', component: () => import('@/views/Settlement/index.vue') },
      { path: '/pay', component: () => import('@/views/Pay/index.vue') },
      { path: '/pay/callback', component: () => import('@/views/Pay/callback.vue') },
      {
        path: '/member',
        component: () => import('@/views/Member/Layout/index.vue'),
        children: [
          { path: '', component: () => import('@/views/Member/Home/index.vue') },
          { path: 'order', component: () => import('@/views/Member/Order/index.vue') }
        ]
      }
    ]
  },
  { path: '/login', component: () => import('@/views/Login/index.vue') },
  { path: '/login/callback', component: () => import('@/views/Login/callback.vue') }
]

const router = createRouter({
  // 🔔VueRouter 官方文档：进阶 - 滚动行为
  scrollBehavior (to, from, savedPosition) {
    if (savedPosition) {
      // console.log('以前的滚动位置', savedPosition)
      return savedPosition
    } else {
      // 滚动到顶部
      // 🔔 Vue2 的坐标是 {x,y}
      // 🔔 Vue3 的坐标是 {top,left}
      return { behavior: 'smooth', top: 0 }
    }
  },
  history: createWebHashHistory(),
  routes
})

// to      去哪里
// from    从哪里来
// next    方向函数
// 路由设计  需要用户登录后才能访问的页面，统一都是 /member 开头
router.beforeEach((to, from, next) => {
  if (to.path.startsWith('/member') && !store.state.user.profile.token) {
    next('/login?redirectUrl=' + to.fullPath)
  } else {
    next()
  }
})

export default router
